﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Globalization;

namespace MvcEngine.Mvc.Extensions
{
    public static class ModelStateDictionaryExtensions
    {
        public static void AddValue(this ModelStateDictionary modelState, string key, string value)
        {
            if (!modelState.ContainsKey(key))
            {
                modelState.Add(key, new ModelState()
                {
                    Value = new ValueProviderResult(value, value, CultureInfo.CurrentCulture)
                });
            }
        }

        public static void AddError(this ModelStateDictionary modelStateDictionary, string key, string error)
        {
            modelStateDictionary.Remove(key);
            var modelState = new ModelState();
            modelState.Errors.Add(error);
            modelStateDictionary.Add(key, modelState);
        }

        public static string[] GetErrors(this ModelStateDictionary modelStateDictionary)
        {
            List<string> result = new List<string>();
            foreach (var item in modelStateDictionary.Values)
            {
                foreach (var error in item.Errors)
                {
                    result.Add(error.ErrorMessage);
                }
            }
            return result.ToArray();
        }


        public static void CopyFrom(this ModelStateDictionary modelState, ModelStateDictionary newModelState)
        {
            foreach (var item in newModelState)
            {
                modelState.Add(item.Key, item.Value);
            }
        }
    }
}
